package main

import (
	"context"
	"flag"
	"goStudy/grpc/route_guide/routeguide"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"io"
	"log"
	"time"
)


var (
	tls=flag.Bool("tls",false,"Connetcion users TLS if true,else plain TCP")
	caFile=flag.String("ca_file","","The flie containing the CA root cert file")
	serverAddr=flag.String("server_addr","127.0.0.1:10000","The server address in the format of host:port")
	serverHostOverride=flag.String("server_host_override","x.test.youtube.com","The server name use to verify the hostname returned by TLS handshake")
)


func printFeature(client routeguide.RouteGuideClient,point *routeguide.Point) {
	log.Printf("Getting feature for point (%d,%d)")
	ctx,cancel:=context.WithTimeout(context.Background(),10*time.Second)
	defer cancel()
	feature,err:=client.GetFeature(ctx,point)
	if err != nil {
		log.Fatalf("%v.GetFeatures(_) = _, %v",client,err)
	}

	log.Println(feature)
}

func printFeatures(client routeguide.RouteGuideClient,rect *routeguide.Rectangle) {
	log.Printf("Looking for features within %v",rect)
	ctx,cancel:= context.WithTimeout(context.Background(),10*time.Second)
	defer cancel()
	stream,err:=client.ListFeatures(ctx,rect)
	if err != nil {
		log.Fatalf("%v.ListFeatures(_)=_, %v",client,err)
	}

	for {
		feature,err:=stream.Recv()
		if err == io.EOF {
			break
		}
		if err!= nil {
			log.Fatalf("%v.ListFeatures(_)=_,%v",client,err)
		}

		log.Println(feature)
	}
}

func main() {
	flag.Parse()

	var opts []grpc.DialOption

	if *tls{
		if *caFile== "" {
			*caFile=testdata.Path("ca.pem")
		}
		creds,err:=credentials.NewClientTLSFromFile(*caFile,*serverHostOverride)

		if err != nil {
			log.Fatalf("Failed to create TLS credentials %v",err)
		}

		opts=append(opts,grpc.WithTransportCredentials(creds))
	} else{
		opts =append(opts,grpc.WithInsecure())
	}

	conn,err:=grpc.Dial(*serverAddr,opts...)
	if err != nil {
		log.Fatalf("fail to dial:%v",err)
	}

	defer conn.Close()
	client:=routeguide.NewRouteGuideClient(conn)

	printFeature(client,&routeguide.Point{Latitude:409146138,Longitude:-746188906})

	// Looking for features between 40, -75 and 42, -73.
	printFeatures(client, &routeguide.Rectangle{
		Lo: &routeguide.Point{Latitude: 400000000, Longitude: -750000000},
		Hi: &routeguide.Point{Latitude: 420000000, Longitude: -730000000},
	})

}
